import { useState, useEffect } from 'react';
import { Layout, Button, Radio, Tabs, ConfigProvider, theme, Tooltip, message } from 'antd';
import { SettingOutlined, MobileOutlined, DesktopOutlined, SendOutlined, EyeOutlined, BulbOutlined } from '@ant-design/icons';
import styled from 'styled-components';
import './App.css';
import type { RadioChangeEvent } from 'antd';

// 导入主题CSS
import './styles/themes/index.css';

// 导入代码块工具函数
import { addCopyButtonsToCodeBlocks, removeCopyButtonsFromCodeBlocks } from './utils/codeBlockUtils.ts';

// Import custom components
import MarkdownEditor from './components/MarkdownEditor';
import PlatformPreview from './components/PlatformPreview';
import PlatformSettings from './components/PlatformSettings';
import PublishModal from './components/PublishModal';
import ThemeSelector from './components/ThemeSelector';
import CssViewer from './components/CssViewer';

// Platform types
type Platform = 'xiaohongshu' | 'wechat' | 'zhihu' | 'toutiao' | 'nowcoder' | 'baijiahao' | 'juejin';
type DeviceType = 'mobile' | 'desktop';

// Platform configuration interface
interface PlatformConfig {
  name: string;
  enabled: boolean;
  credentials: Record<string, string>;
}

const { Header, Sider, Content } = Layout;

const ToolbarContainer = styled.div`
  display: flex;
  justify-content: space-between;
  padding: 8px 16px;
  border-bottom: 1px solid ${props => props.theme.isDark ? '#303030' : '#f0f0f0'};
  background-color: ${props => props.theme.isDark ? '#1f1f1f' : '#fff'};
`;

const EditorContainer = styled.div`
  height: calc(100% - 41px); /* 减去ThemeToolbar的高度 */
  overflow: auto;
`;

const PreviewContainer = styled.div`
  height: 100%;
  overflow: auto;
  background-color: ${props => props.theme.isDark ? '#1f1f1f' : '#fff'};
`;

const ThemeToolbar = styled.div`
  display: flex;
  align-items: center;
  padding: 8px 16px;
  border-bottom: 1px solid #f0f0f0;
  background-color: ${props => props.theme.isDark ? '#1f1f1f' : '#fff'};
  position: sticky;
  top: 0;
  z-index: 10;
`;

function App() {
  // State management
  const [markdown, setMarkdown] = useState<string>(`# 内容发布助手

开始编写你的内容...`);
  const [selectedPlatform, setSelectedPlatform] = useState<Platform>('xiaohongshu');
  const [deviceType, setDeviceType] = useState<DeviceType>('mobile');
  const [isDarkMode, setIsDarkMode] = useState<boolean>(false);
  const [isSettingsModalOpen, setIsSettingsModalOpen] = useState<boolean>(false);
  const [isPublishModalOpen, setIsPublishModalOpen] = useState<boolean>(false);
  const [isCssViewerOpen, setIsCssViewerOpen] = useState<boolean>(false);
  const [markdownTheme, setMarkdownTheme] = useState<string>('default');
  const [codeBlockTheme, setCodeBlockTheme] = useState<string>('github');
  const [platformConfigs, setPlatformConfigs] = useState<Record<Platform, PlatformConfig>>({  
    xiaohongshu: { name: '小红书', enabled: true, credentials: {} },
    wechat: { name: '微信公众号', enabled: true, credentials: {} },
    zhihu: { name: '知乎', enabled: true, credentials: {} },
    toutiao: { name: '今日头条', enabled: true, credentials: {} },
    nowcoder: { name: '牛客', enabled: true, credentials: {} },
    baijiahao: { name: '百家号', enabled: true, credentials: {} },
    juejin: { name: '掘金', enabled: true, credentials: {} },
  });
  
  // 添加代码块复制按钮
  useEffect(() => {
    // 等待DOM渲染完成后添加复制按钮
    const timer = setTimeout(() => {
      addCopyButtonsToCodeBlocks();
    }, 500);
    
    // 组件卸载时清理
    return () => {
      clearTimeout(timer);
      removeCopyButtonsFromCodeBlocks();
    };
  }, [markdown, markdownTheme, codeBlockTheme]); // 当内容或主题变化时重新添加按钮
  
  // Load saved configurations from localStorage if available
  useEffect(() => {
    const savedConfigs = localStorage.getItem('platformConfigs');
    if (savedConfigs) {
      try {
        setPlatformConfigs(JSON.parse(savedConfigs));
      } catch (error) {
        console.error('Failed to parse saved configurations:', error);
      }
    }
    
    // Load theme preference
    const savedTheme = localStorage.getItem('isDarkMode');
    if (savedTheme) {
      setIsDarkMode(savedTheme === 'true');
    }

    // Load markdown theme
    const savedMarkdownTheme = localStorage.getItem('markdownTheme');
    if (savedMarkdownTheme) {
      setMarkdownTheme(savedMarkdownTheme);
    }

    // Load code block theme
    const savedCodeBlockTheme = localStorage.getItem('codeBlockTheme');
    if (savedCodeBlockTheme) {
      setCodeBlockTheme(savedCodeBlockTheme);
    }
  }, []);
  
  // Handle markdown content change
  const handleMarkdownChange = (newValue: string) => {
    setMarkdown(newValue);
  };

  // Handle platform change
  const handlePlatformChange = (platform: string) => {
    setSelectedPlatform(platform as Platform);
  };

  // Handle device type change
  const handleDeviceTypeChange = (e: RadioChangeEvent) => {
    setDeviceType(e.target.value as DeviceType);
  };

  // Toggle theme
  const toggleTheme = () => {
    const newThemeValue = !isDarkMode;
    setIsDarkMode(newThemeValue);
    localStorage.setItem('isDarkMode', String(newThemeValue));
  };

  // Handle markdown theme change
  const handleMarkdownThemeChange = (theme: string) => {
    setMarkdownTheme(theme);
    localStorage.setItem('markdownTheme', theme);
  };

  // Handle code block theme change
  const handleCodeBlockThemeChange = (theme: string) => {
    setCodeBlockTheme(theme);
    localStorage.setItem('codeBlockTheme', theme);
  };

  // Open settings modal
  const showSettingsModal = () => {
    setIsSettingsModalOpen(true);
  };

  // Handle settings modal close
  const handleSettingsCancel = () => {
    setIsSettingsModalOpen(false);
  };

  // Handle settings form submit
  const handleSettingsSubmit = (values: Record<string, string>) => {
    // Update platform configurations
    const updatedConfigs = { ...platformConfigs };
    Object.keys(values).forEach((key) => {
      const [platform, field] = key.split('_');
      if (platform && field && Object.keys(platformConfigs).includes(platform)) {
        updatedConfigs[platform as Platform].credentials[field] = values[key];
      }
    });
    
    // Save to state and localStorage
    setPlatformConfigs(updatedConfigs);
    localStorage.setItem('platformConfigs', JSON.stringify(updatedConfigs));
    setIsSettingsModalOpen(false);
    message.success('配置已保存');
  };

  // Open publish modal
  const showPublishModal = () => {
    setIsPublishModalOpen(true);
  };

  // Handle publish modal close
  const handlePublishCancel = () => {
    setIsPublishModalOpen(false);
  };

  // Open CSS viewer modal
  const showCssViewer = () => {
    setIsCssViewerOpen(true);
  };

  // Handle CSS viewer modal close
  const handleCssViewerClose = () => {
    setIsCssViewerOpen(false);
  };

  // Handle publish to platforms
  const handlePublish = (selectedPlatforms: Platform[]) => {
    // Mock publishing to selected platforms
    console.log('Publishing to platforms:', selectedPlatforms);
    console.log('Content:', markdown);
    
    // In a real application, you would make API calls to publish to each platform
    message.success(`已成功发布到 ${selectedPlatforms.map(p => platformConfigs[p].name).join('、')}`);
    setIsPublishModalOpen(false);
  };

  return (
    <ConfigProvider
      theme={{
        algorithm: isDarkMode ? theme.darkAlgorithm : theme.defaultAlgorithm,
      }}
    >
      <Layout style={{ height: '100vh' }} className={isDarkMode ? 'dark-mode' : ''}>
        <Header style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 16px' }}>
          <div style={{ color: 'white', fontSize: '18px', fontWeight: 'bold' }}>内容发布助手</div>
          <div>
            <Button 
              type="primary" 
              icon={<SendOutlined />} 
              onClick={showPublishModal}
              style={{ marginRight: '8px' }}
            >
              发布
            </Button>
            <Button 
              icon={<SettingOutlined />} 
              onClick={showSettingsModal}
              style={{ marginRight: '8px' }}
            />
            <Button
              icon={<EyeOutlined />}
              onClick={showCssViewer}
              style={{ marginRight: '8px' }}
            />
            <Button
              icon={<BulbOutlined />}
              onClick={toggleTheme}
            />
          </div>
        </Header>
        <Layout>
          <Layout style={{ flex: 1 }}>
            <Layout style={{ height: 'calc(100vh - 56px)' }}>
              <Sider width="50%" theme={isDarkMode ? 'dark' : 'light'} style={{ overflow: 'hidden' }}>
                <ThemeToolbar theme={{ isDark: isDarkMode }}>
                  <ThemeSelector
                    currentTheme={markdownTheme}
                    onThemeChange={handleMarkdownThemeChange}
                    themeType="markdown"
                    isDarkMode={isDarkMode}
                  />
                  <ThemeSelector
                    currentTheme={codeBlockTheme}
                    onThemeChange={handleCodeBlockThemeChange}
                    themeType="codeBlock"
                    isDarkMode={isDarkMode}
                  />
                </ThemeToolbar>
                <EditorContainer>
                  <MarkdownEditor 
                    value={markdown} 
                    onChange={handleMarkdownChange} 
                    isDarkMode={isDarkMode}
                  />
                </EditorContainer>
              </Sider>
              <Content style={{ position: 'relative' }}>
                <ToolbarContainer theme={{ isDark: isDarkMode }}>
                  <Tabs 
                    activeKey={selectedPlatform}
                    onChange={handlePlatformChange}
                    items={[
                      { key: 'xiaohongshu', label: '小红书' },
                      { key: 'wechat', label: '微信公众号' },
                      { key: 'zhihu', label: '知乎' },
                      { key: 'toutiao', label: '今日头条' },
                      { key: 'nowcoder', label: '牛客' },
                      { key: 'baijiahao', label: '百家号' },
                      { key: 'juejin', label: '掘金' },
                    ]}
                  />
                  <Radio.Group value={deviceType} onChange={handleDeviceTypeChange}>
                    <Tooltip title="手机预览">
                      <Radio.Button value="mobile"><MobileOutlined /></Radio.Button>
                    </Tooltip>
                    <Tooltip title="电脑预览">
                      <Radio.Button value="desktop"><DesktopOutlined /></Radio.Button>
                    </Tooltip>
                  </Radio.Group>
                </ToolbarContainer>
                <PreviewContainer theme={{ isDark: isDarkMode }}>
                  <PlatformPreview 
                    markdown={markdown}
                    platform={selectedPlatform}
                    deviceType={deviceType}
                    isDarkMode={isDarkMode}
                    markdownTheme={markdownTheme}
                    codeBlockTheme={codeBlockTheme}
                  />
                </PreviewContainer>
              </Content>
            </Layout>
          </Layout>
        </Layout>
        
        {/* Settings Modal */}
        <PlatformSettings 
          open={isSettingsModalOpen}
          onCancel={handleSettingsCancel}
          onSave={handleSettingsSubmit}
          platformConfigs={platformConfigs}
        />
        
        {/* Publish Modal */}
        <PublishModal 
          open={isPublishModalOpen}
          onCancel={handlePublishCancel}
          onPublish={handlePublish}
          platformConfigs={platformConfigs}
          content={markdown}
        />

        {/* CSS Viewer Modal */}
        <CssViewer
          open={isCssViewerOpen}
          onClose={handleCssViewerClose}
          markdownTheme={markdownTheme}
          codeBlockTheme={codeBlockTheme}
          isDarkMode={isDarkMode}
        />
      </Layout>
    </ConfigProvider>
  )
}

export default App
